12. Navigation After Login

L6 A12 Navigation After Login

So far, you’ve successfully set up your app to redirect the user to the login screen if they try to access the Settings screen without being logged in.

However, you might have noticed that after you go through the sign in flow, you are brought back to the Login screen again. This is not a good user experience and can be confusing to the user.

To provide the ideal user experience, the app should bring the user back to the Settings screen after the user successfully logs in.

  1. In LoginFragment.kt’s onViewCreated(), observe the authenticationState and navigate the user back to SettingsFragment when they are successfully authenticated.

LoginFragment.kt

// Observe the authentication state so we can know if the user has logged in successfully.
// If the user has logged in successfully, bring them back to the settings screen.
// If the user did not log in successfully, display an error message.
viewModel.authenticationState.observe(viewLifecycleOwner, Observer { authenticationState ->
   when (authenticationState) {
       LoginViewModel.AuthenticationState.AUTHENTICATED -> navController.popBackStack()
       else -> Log.e(
           TAG,
           "Authentication state that doesn't require any UI change $authenticationState"
       )
   }
})
  1. Run your app again and confirm that now when you successfully sign in, you land on the Settings page instead of the Login page.
Popping the Back Stack
As the user progresses through an app, Android keeps track of the screens they visit. When the user presses the back button, the app goes back through the visited screens in order.

When you pop a screen off the backstack, you are basically telling Android to skip that screen when the user presses the back button.

In this case, you are removing the current screen from the back stack so that when the user presses the back button, the app skips this screen and goes back to the screen that the user visited before visiting this one.

In other words, when the user presses the back button, the app does not come back to the login screen, instead it goes to the screen that the user visited before coming to the login screen.